iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 2
0
自我挑戰組

各種筆記系列 第 2

[Kata] Clojure - Day 2

  • 分享至 

  • xImage
  •  

String repeat

依據給予的次數重複字串
Write a function called repeat_str which repeats the given string src exactly count times.

repeatStr(6, "I") // "IIIIII"
repeatStr(5, "Hello") // "HelloHelloHelloHelloHello"

Solution 1:

(ns clojure.string-repeat)

(defn repeat-str [n strng]
  (apply str (repeat n strng)))
(repeat 2 "I")             ;; ("I" "I")

(str "I" "I")              ;; "II"
(apply str "I" "I")        ;; "II"

(str (repeat 2 "I"))       ;; "(\"I\" \"I\")"
;; str is common to apply to an existing collection, compare with the previous example
(apply str (repeat 2 "I")) ;; "II"

Solution 2:

;; (join separator coll) Returns a string of all elements in coll, as returned by (seq coll), separated by an optional separator.

(ns clojure.string-repeat)

(defn repeat-str [n str]
  (clojure.string/join (repeat n str)))

上一篇
[Kata] Clojure - Day 1
下一篇
[Kata] Clojure - Day 3
系列文
各種筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言